package com.lagou.edu.zdy.rpc;

import com.lagou.edu.Spring.ApplicationContext;
import com.lagou.edu.zdy.util.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 接收用户请求，处理并响应用户结果
 */
public class UserServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)  {
        RpcRequest request = (RpcRequest) msg;
        System.out.println("服务端收到请求："+request);
        //根据类名获取全限定名
        String fullClassName = ApplicationContext.getFullClassName(request.getClassName());
        if (fullClassName!=null) {
            //通过ioc容器获取对象，并执行方法
            Object o = ApplicationContext.ioc.get(fullClassName);
            if (o!=null){
                try {
                    Method[] methods = o.getClass().getMethods();
                    for (Method method : methods) {
                        if(method.getName().equals(request.getMethodName())){
                            Object result = method.invoke(o, request.getParameters());
                            System.out.println(result);
                            ctx.writeAndFlush(result);
                            break;
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
